package wawi.actions;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import wawi.db.DbConnector;
import wawi.util.Props;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BarcodeEAN;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class BarcodeServlet extends HttpServlet
{

	private final static float P_CM = 28.346f;
	
	private final static float W_CM = 5.25f;
	private final static float H_CM = 2.97f;
	
	private final static float WIDTH = W_CM * P_CM;
	private final static float HEIGHT = H_CM * P_CM;
	
	
	
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException
    {                
        try
        {
        	int recid = Integer.parseInt(req.getParameter("bestellung"));
        	int versatz = Integer.parseInt(req.getParameter("versatz"));        	
        	Bestellung bestellung = DbConnector.getInstance().readBestellung(recid);
        	
        	List<ArtikelDetails> details = new ArrayList<ArtikelDetails>();
        	bestellung.loadPositions();
        	
        	for (int i=0; i<versatz; i++)
        		details.add(null);
        	
        	for (BestellungPosition pos : bestellung.getPositionen())
        	{
        		for (int i=0; i<pos.getMenge(); i++)
        			details.add(pos.getArtikelDetails());
        	}
        	
        	
        	//Write PDF to response
            ByteArrayOutputStream out = new ByteArrayOutputStream();             
            Document document = new Document();          
            PdfWriter writer = PdfWriter.getInstance(document, out);
            document.open();                                             
            PdfContentByte cb = writer.getDirectContent();
            
            int pos = 0;
            
            do
            {
    	        //Etikett
    	        float x = 0;
    	        float y = 9*HEIGHT;	        
    	        
    	        for (int i=0; i<10; i++) // 10 Zeilen
    	        {
    	        	x = 0;
    	        	
    	        	for (int j=0; j<4; j++) // 4 Spalten
    	        	{
    	        		if (pos < details.size())
    	        		{
    	        			ArtikelDetails ad = details.get(pos);        			
    	        			pos++;
    	        			
    	        			if (ad!=null) //null ist versatz
    	        				drawEtikett(cb, x, y, ad.getArtikel(), ad);
    	        			
    	        			x += WIDTH;
    	        		}
    	        	}        	
    	        	y -= HEIGHT;
    	        }
    	        
    	        if (pos<details.size())
    	        	document.newPage();
            }
            while (pos < details.size());
            
            
            
            
            //Send Data
            document.close();
            
            res.setContentType("application/pdf");
            res.setHeader("Content-disposition", "attachment; filename=\"barcodes.pdf\"");            
            res.setContentLength(out.size());
            
            out.writeTo(res.getOutputStream());
            res.getOutputStream().flush();
        }
        catch (NumberFormatException nfe)
        {
            nfe.printStackTrace();            
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new IOException(e.toString());
        }
    }
    
	private void drawEtikett(PdfContentByte cb, float x, float y, Artikel art, ArtikelDetails details) throws DocumentException, IOException
	{
		
    	BaseFont bf = BaseFont.createFont(
    			BaseFont.HELVETICA,
    			BaseFont.CP1252,
    			BaseFont.NOT_EMBEDDED);
    	
    	BaseFont bf_bold = BaseFont.createFont(
    			BaseFont.HELVETICA_BOLD,
    			BaseFont.CP1252,
    			BaseFont.NOT_EMBEDDED);
		
		float d_x = 33f;
		float d_y = 10f;
		
		// EAN 13
        BarcodeEAN codeEAN = new BarcodeEAN();       
        codeEAN.setBarHeight(25f);       
        codeEAN.setCode(details.getPrintEAN());          
        
        //Artikel-Name
        cb.beginText();
        cb.setFontAndSize(bf, 8);
        cb.setTextMatrix( x + d_x  -0.6f*P_CM, y + d_y + 55f);
        cb.showText(art.getEtikettName());
        cb.endText();
        
        
        
        //Preis
    	DecimalFormat df = new DecimalFormat("0.00");		
        cb.beginText();
        cb.setTextMatrix( x +d_x, y + d_y + 47f);
        cb.setFontAndSize(bf, 5);
        cb.showText("EUR ");
        cb.setFontAndSize(bf_bold, 6);
        cb.showText(df.format(art.getPreisVK()));    
        cb.endText();
        
        
        
        //Details
        cb.beginText();
        
        cb.setTextMatrix( x +d_x, y + d_y + 39f);
        
        cb.setFontAndSize(bf, 5);
        cb.showText("ART ");
        
        cb.setFontAndSize(bf_bold, 6);
        cb.showText(""+art.getArtNr());       
        
        cb.setFontAndSize(bf, 5);
        cb.showText("  COL ");
        
        cb.setFontAndSize(bf_bold, 6);
        cb.showText(details.getFarbe());
        
        cb.setFontAndSize(bf, 5);
        cb.showText("  SIZE ");
        
        cb.setFontAndSize(bf_bold, 6);
        cb.showText(details.getGroesse());
        
        cb.endText();
        
        
        //Barcode
        Image img = codeEAN.createImageWithBarcode(cb, null, null);
        
        
        
        //Position + Add
        img.setAbsolutePosition(x + d_x, y + d_y);
        cb.addImage(img);

        //Rahmen
        if (Props.isBool("barcode.rahmen", false))
        {
	        cb.saveState();
	        cb.rectangle(x + 0f, y+0f, W_CM*P_CM, H_CM*P_CM);
	        cb.stroke();
	        cb.restoreState();
        }
	}
}
